package com.Cychat.auth.utils;

import com.Cychat.auth.config.WechatMiniAppProperties;
import com.Cychat.auth.entity.DO.WxParamsDO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Auther: 刘博文
 * Date: 2025/10/29:10:57
 * Description: 获取微信openid服务
 */
@Service
public class GetWxOpenid {
    @Autowired
    private WechatMiniAppProperties wechatMiniAppProperties;

    /**
     * 调用微信接口获取openid
     * @param code 微信登录凭证
     * @return openid
     */
    public WxParamsDO getOpenidFromWechat(String code) {
        // 构建请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                wechatMiniAppProperties.getAppid() +
                "&secret=" + wechatMiniAppProperties.getSecret() +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        try {
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();

            // 发起GET请求
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            // 解析返回的JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.getBody());

            // 检查是否有错误
            if (jsonNode.has("errcode") && jsonNode.get("errcode").asInt() != 0) {
                // 处理错误情况
                int errcode = jsonNode.get("errcode").asInt();
                String errmsg = jsonNode.has("errmsg") ? jsonNode.get("errmsg").asText() : "未知错误";
                throw new RuntimeException("微信接口调用失败，错误码: " + errcode + "，错误信息: " + errmsg);
            }

            // 返回openid和session_key
            WxParamsDO wxParamsDO = new WxParamsDO();
            wxParamsDO.setOpenid(jsonNode.get("openid").asText());
            wxParamsDO.setSessionKey(jsonNode.get("session_key").asText());
            return wxParamsDO;
        } catch (Exception e) {
            throw new RuntimeException("获取微信openid失败: " + e.getMessage(), e);
        }
    }
}
